/* eslint-disable no-param-reassign */
<template>
  <div class="positionMgn">
    <GeminiScrollbar class="container" @ready="initScrollbar" :autoshow="true">
      <div class="table-header">
        <p>职位列表</p>
        <div class="search-bar">
          <input v-model="name" type="text" placeholder="职位名称" @keyup.enter="findPos">
          <div class="btn primary" style="margin-right:5px" @click="findPos">搜索</div>
          <div class="btn primary" @click="addPositionClicked">添加</div>
        </div>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th></th>
            <th>职位名称</th>
            <th>工作城市</th>
            <th>所需学历</th>
            <th>工作经验</th>
            <th>薪资范围</th>
            <th>工作地点</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="pos of tableData">
            <tr :key="pos.id">
              <td class="expend">
                <img @click="expend($event)" src="@/assets/img/u4210.png"/>
              </td>
              <td>{{ pos.name }}</td>
              <td>{{ pos.cityName }}</td>
              <td>{{ pos.eduName }}</td>
              <td>{{ pos.expName }}</td>
              <td>{{ pos.minSalary + '~' + pos.maxSalary + '元/月' }}</td>
              <td>{{ pos.loc }}</td>
              <td>
                <a @click="modifyPositionClicked(pos)">修改</a>
                <a @click="deletePos(pos.id)">删除</a>
              </td>
            </tr>
            <tr :key="pos.id + 10000" style="display:none">
              <td class="middle-container" colspan="8">
                <div class="middle">
                  职位描述：{{ pos.desc }}
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </GeminiScrollbar>
    <footer>
      <Page @setCurPage="setCurPage" :curPage="curPage" :total="total" :pageSize="pageSize"></Page>
    </footer>
    <position-dialog
      @close="addPositionShow = false"
      @done="addPosition"
      :dialogData="{}"
      title="添加职位"
      :show="addPositionShow"
    ></position-dialog>
    <position-dialog
      @close="modifyPositionShow = false"
      @done="modifyPosition"
      :dialogData="modifyPositionData"
      title="修改职位信息"
      :show="modifyPositionShow"
    ></position-dialog>
  </div>
</template>
<script>
/* eslint-disable no-param-reassign */
import Page from '@/components/Pages/index';
import PositionDialog from '@/components/Dialogs/addPosition';
import api from '@/api/positionMgn';

function getEduName(id) {
  switch (id) {
    case '0':
      return '不限';
    case '1':
      return '小学';
    case '2':
      return '初中';
    case '3':
      return '高中';
    case '4':
      return '专科';
    case '5':
      return '本科';
    case '6':
      return '研究生';
    case '7':
      return '博士';
    default:
      return null;
  }
}

function getExpName(id) {
  switch (id) {
    case '0':
      return '不限';
    case '1':
      return '应届生';
    case '2':
      return '一年以内 ';
    case '3':
      return '一到三年';
    case '4':
      return '三到五年';
    case '5':
      return '五到十年';
    case '6':
      return '五年以上';
    default:
      return null;
  }
}

function getCityName(id, citys) {
  for (let i = 0; i < citys.length; i += 1) {
    if (citys[i].businessId === id) {
      return citys[i].name;
    }
  }
  return null;
}
async function getCity() {
  const response = await api.getCityApi();
  return response.data.data;
}
async function getBJobsAndUser(curPage, name, citys) {
  const tableData = [];
  const params = new URLSearchParams();
  params.append('recruiterId', sessionStorage.getItem('recruiterId'));
  params.append('name', name);
  params.append('rows', 10);
  params.append('page', curPage);
  const response = await api.getBJobsAndUserApi(params);
  const datas = response.data.rows;
  const total = response.data.total;
  for (let i = 0; i < datas.length; i += 1) {
    tableData.push({
      id: datas[i].bjob.businessId,
      name: datas[i].bjob.name,
      city: datas[i].bjob.expectCity,
      cityName: getCityName(datas[i].bjob.expectCity, citys),
      edubg: datas[i].bjob.educated,
      eduName: getEduName(datas[i].bjob.educated),
      exp: datas[i].bjob.experience,
      expName: getExpName(datas[i].bjob.experience),
      minSalary: datas[i].bjob.minSalary,
      maxSalary: datas[i].bjob.maxSalary,
      loc: datas[i].bjob.cityDesc,
      desc: datas[i].bjob.description,
      worktype: datas[i].bjob.jobType,
    })
    ;
  }
  return [total, tableData];
}
export default {
  name: 'PositionMgn',
  data() {
    return {
      name: '',
      tableData: [
      ],

      curPage: 1,
      total: 1000,
      pageSize: 10,

      addPositionShow: false,
      modifyPositionShow: false,
      modifyPositionData: null,
      allCity: [],

      scrollObj: null,
    };
  },
  beforeRouteEnter(to, from, next) {
    if (sessionStorage.getItem('userToken') === null || sessionStorage.getItem('loginType') !== '3') {
      next({ path: '/login' });
    }
    getCity().then((citys) => {
      getBJobsAndUser(1, '', citys).then((jobs) => {
        next((vm) => {
          vm.$emit('route-switch', window.location.href.split('/').pop());
          vm.total = jobs[0];
          vm.tableData = [...jobs[1]];
          vm.allCity = [...citys];
        });
      });
    });
  },
  methods: {
    async setCurPage(page) {
      this.curPage = page;
      const jobs = await getBJobsAndUser(page, this.name, this.allCity);
      this.total = jobs[0];
      this.tableData = [...jobs[1]];
    },
    expend(e) {
      if (e.currentTarget.className === '') {
        e.currentTarget.className = 'rotate';
      } else {
        e.currentTarget.className = '';
      }
      const display = e.currentTarget.parentNode.parentNode.nextSibling.nextSibling.style.display;
      if (display === 'none') {
        e.currentTarget.parentNode.parentNode.nextSibling.nextSibling.style.display = '';
      } else {
        e.currentTarget.parentNode.parentNode.nextSibling.nextSibling.style.display = 'none';
      }
      this.scrollObj.update();
    },
    addPositionClicked() {
      this.addPositionShow = true;
    },
    addPosition(pos) {
      this.addPositionShow = false;
      const params = new URLSearchParams();
      params.append('recruiterId', this.$store.getters['user/getUserInfo'].recruiterId);
      params.append('name', pos.name);
      params.append('description', pos.desc);
      params.append('expectCity', pos.city);
      params.append('cityDesc', pos.loc);
      params.append('educated', pos.edubg);
      params.append('experience', pos.exp);
      params.append('jobType', pos.worktype);
      params.append('minSalary', pos.minSalary);
      params.append('maxSalary', pos.maxSalary);
      api.addApi(params).then(async (response) => {
        if (response.data.code === 200) {
          this.$alert('添加成功');
          const jobs = await getBJobsAndUser(this.curPage, this.name, this.allCity);
          this.total = jobs[0];
          this.tableData = [...jobs[1]];
        } else {
          this.$alert(response.data.message);
        }
      });
    },
    modifyPositionClicked(pos) {
      this.modifyPositionShow = true;
      this.modifyPositionData = { ...pos };
    },
    modifyPosition(pos) {
      this.modifyPositionShow = false;
      const params = new URLSearchParams();
      params.append('recruiterId', this.$store.getters['user/getUserInfo'].recruiterId);
      params.append('name', pos.name);
      params.append('description', pos.desc);
      params.append('expectCity', pos.city);
      params.append('cityDesc', pos.loc);
      params.append('educated', pos.edubg);
      params.append('experience', pos.exp);
      params.append('jobType', pos.worktype);
      params.append('minSalary', pos.minSalary);
      params.append('maxSalary', pos.maxSalary);
      api.updateApi(pos.id, params).then(async (response) => {
        if (response.data.code === 200) {
          this.$alert('添加成功');
          const jobs = await getBJobsAndUser(this.curPage, this.name, this.allCity);
          this.total = jobs[0];
          this.tableData = [...jobs[1]];
        } else {
          this.$alert(response.data.message);
        }
      });
    },
    deletePos(posId) {
      this.$confirm('确定要删除该职位吗?', (res) => {
        if (res) {
          api.deleteApi(posId).then(async (response) => {
            if (response.data.code === 200) {
              this.$alert('删除成功');
              const jobs = await getBJobsAndUser(this.curPage, this.name, this.allCity);
              this.total = jobs[0];
              this.tableData = [...jobs[1]];
            } else {
              this.$alert(response.data.message);
            }
          });
        }
      });
    },
    async findPos() {
      const jobs = await getBJobsAndUser(this.curPage, this.name, this.allCity);
      this.total = jobs[0];
      this.tableData = [...jobs[1]];
    },
    initScrollbar(bar) {
      this.scrollObj = bar;
    },
  },
  components: {
    Page,
    PositionDialog,
  },
};
</script>
<style lang="less">
@import url(../../../../static/style/site.comm.less);
@import url(../../../../static/style/site.vars.less);

.positionMgn {
  box-shadow: 0 3px 6px rgba(6,0,1,.05);
  &>.container {
    background: #fff;
    position: relative;
    height: 701px;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display: none;
    }
    .table-header {
      position: sticky;
      top: 0;
    }
    .middle-container {
      box-sizing: border-box;
      padding: 10px;
      padding-left: 40px;
      background: rgb(238, 238, 238);
      height: 100px;
      // display: none;
      .middle {
        text-align: left;
      }
    }
  }
  & > footer {
    padding: 20px 0 20px 0;
    width: 100%;
    background: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
  }
}
</style>
